//
//  NetWorkTools.swift
//  我的微博
//
//  Created by ZhangChao on 15/9/3.
//  Copyright © 2015年 ZhangChao. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}
class NetWorkTools: AFHTTPSessionManager {

    private let clientId = "1216907569"
    private let appSecret = "5b2c9b2e0ff871737a656fa8d178c160"
    let redirectUrl = "http://www.baidu.com"
    
    // 单例

    static let sharedTools: NetWorkTools = {
        
        // 指定 baseURL
        var instance = NetWorkTools(baseURL: nil)
        
        // 设置反序列化的支持格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    // oAuth
    var oAuthUrl : NSURL{
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
        
    }
    // 获取token
    func loadAccessToken(code: String) -> RACSignal{
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameter = ["client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUrl
        ];
        
        // 测试代码?
        
        return request(.POST, URLString: urlString, parameters: parameter, withToken: false)
    }
    // 获取个人信息
    // see[http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show )
    func loadUserInfor(uid: String) -> RACSignal{
        
        let urlString = "https://api.weibo.com/2/users/show.json"

        // 这里去掉了token
        let parameter = ["uid":uid]
        
        return request(.GET, URLString: urlString, parameters: parameter)
    }
    
    // 加载微博数据
    func loadStatus() -> RACSignal{

        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        return request(.GET, URLString: urlString, parameters: nil)
        
    }
    
    // 网络请求方法
    private func request(method: RequestMethod, URLString: String, var parameters: [String: AnyObject]?,withToken: Bool = true ) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            // 0. 判断是否有token
            
            if withToken{
                
                // 判断token是否存在
                guard let token = UserAccountViewModel.sharedUserAccount.accessToken else{
                    
                    // 发送一个错误信息,提示用户现在token没有值
                    subscriber.sendError(NSError(domain: "com.ZC.error", code: 1002, userInfo: ["error":"token 为空"]))
                    
                    return nil
                }
                
                // 判断是否传递了参数字典
                if parameters == nil {
                    
                    parameters = [String :AnyObject]()
                }
                
                // 在参数字典中添加token
                
                parameters!["access_token"] = token
                
            }
            
            // 1. 成功的回调闭包
            let successCallBack = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
                // 将结果发送给订阅者
                subscriber.sendNext(result)
                // 完成
                subscriber.sendCompleted()
            }
            
            // 2. 失败的回调闭包
            let failureCallBack = { (task: NSURLSessionDataTask, error: NSError) -> Void in
                print(error)
                subscriber.sendError(error)
            }
            
            // 3. 根据方法，选择调用不同的网络方法
            // if method == RequestMethod.GET {
            if method == .GET {
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            } else {
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }
            
            return nil
        })
    }

}
